import React, { useState, useEffect } from "react";
import storeutil from "../../util/storeutil";
import { withRouter } from "react-router-dom";
import menuList from "../../config/menuConfig";
import { formdateDate } from "../../util/datatutil";
import { Modal } from "antd";

var intervalId;
function Header(props) {
  const [currentTime, setCurrentTime] = useState(formdate(Date.now()));
  const getTime = () => {
    this.intervalId = setInterval(() => {
      const currentTime = formdateDate(Date.now());
      setCurrentTime(currentTime);
    }, 1000);
  };
  const getTitle = () => {
    const path = props.location.pathname;
    let title;
    menuList.forEach((item) => {
      if (item.key == path) {
        title = item.title;
      } else if (item.children) {
        const cItem = item.children.find(
          (cItem) => path.indexOf(cItem.key) == 0
        );
        if (cItem) {
          title = cItem.title;
        }
      }
    });
    return title;
  };
  useEffect(() => {
    getTime();
    return () => {
      clearInterval(this.intervalId);
    };
  }, []);
  const logout = () => {
    Modal.confirm({
      content: "确定退出?",
      onOk: () => {
        console.log("OK", this);
        storeutil.removeUser();
        props.history.replace("/login");
      },
    });
  };
  const user = storeutil.getUser();
  const { username } = user;

  return (
    <div className="Header">
      <span>欢迎{username}</span>
      <span>当前时间:{currentTime}</span>
      <span>当前位置:{getTitle()}</span>
      <button type="primary" onClick={logout}>
        退出
      </button>
    </div>
  );
}

export default withRouter(Header);
